package com.cash.lemoloan.statisticlib.Utils;

import android.os.Build;
import android.text.TextUtils;

import java.util.Arrays;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AesNumberCipherHelper {

    private static String aesKey = "";

    public static String getAesKey() {
        return aesKey;
    }

    public static void setAesKey(String aesKey) {
        AesNumberCipherHelper.aesKey = aesKey;
    }

    public static String encrypt(String content) {
        if (TextUtils.isEmpty(content)) {
            return null;
        } else {

            try {
                Cipher cipher = getCipher();
                byte[] aesKeys = getAesCipherKey(aesKey);
                init(cipher, Cipher.ENCRYPT_MODE, aesKeys);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    byte[] encrypted = cipher.doFinal(content.getBytes("UTF-8"));
                    return Base64.getEncoder().encodeToString(encrypted);
                }
                return null;
            } catch (Exception var7) {
                throw new IllegalStateException("failed to encrypt the secure field.");
            }
        }
    }

    public static String decrypt(String content) {
        if (TextUtils.isEmpty(content)) {
            return null;
        } else {

            try {
                Cipher cipher = getCipher();
                byte[] aesKeys = getAesCipherKey(aesKey);
                init(cipher, Cipher.DECRYPT_MODE, aesKeys);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(content));
                    return new String(decrypted, "UTF-8");
                }
                return null;
            } catch (Exception var8) {
                throw new IllegalStateException("failed to decrypt the secure field.");
            }
        }
    }


    private static void init(Cipher cipher, int mode, byte[] secretKeys) throws Exception {
        cipher.init(mode, new SecretKeySpec(secretKeys, "AES"), new IvParameterSpec(Arrays.copyOfRange(secretKeys, 0, 16)));
    }

    private static Cipher getCipher() {
        try {
            return Cipher.getInstance("AES/CBC/PKCS5Padding");
        } catch (Exception var1) {
            throw new IllegalStateException(var1);
        }
    }

    private static byte[] getAesCipherKey(String key) {
        try {
            return HEX.encodeHexStr(key.getBytes()).substring(0,16).getBytes("UTF-8");
        } catch (Exception var2) {
            throw new IllegalStateException("NoSuchAlgorithmException,stop!");
        }
    }

}
